/*
 * @Description: 相关数据共用
 */
import api from '@/api';
import emitter from "@/plugins/global-callback";
import globalData from "@/plugins/data";

export default {
    props: {
        //当前栏目数据
        data: {
            type: Object,
        },
        //获取当前栏目传的参数
        params: {
            type: Object,
        },
        //基础数据
        baseInfo: {
            type: Object,
        },
        //是否是处理页面
        isSummary: {
            type: Boolean,
        },
    },
    data() {
        return { list: [], isCanCopy: globalData.isCap4 };
    },
    async created() {
        await this.initData();
        let zwIframe = window._getZWIframe();
        //注册绑定表单修改数据的事件
        if (zwIframe?.contentAPI?.registerEvent) {
            this.registerEvent();
        }else {
            //等待加载完毕
            emitter.subscribe('ContentLoaded',this.registerEvent);
        }
    },
    methods: {
       async initData(useCondition=false){
           const { businessData } = this.baseInfo;
           const { id: memberId } = businessData.currentUser;
           const { state: affairState } = businessData.affair;
           const { template } = businessData;
           const pageConditions={};
           pageConditions[this.data.id.toString()]=[]
           this.isCanCopy = globalData.isCap4 && template?.canCopy || false;
           let zwIframe = window._getZWIframe();
           let nodePolicy = businessData?.nodePolicy?.permissionName||'';
           const formDataId = zwIframe.contentAPI.getContentDataId();
           
           if (useCondition){
               pageConditions[this.data.id.toString()]=this.data.customCondItemList.filter(item=>item.changed);
           }
           const requestData = (
             await api.relationDataGetMyLaunchData(
               Object.assign(
                 {
                     memberId, //用户id
                     dataRelationCfgIds: [this.data.id.toString()], //相关数据的配置id，由相关数据配置接口返回的对象id组成
                     pageConditions: pageConditions,
                     affairState, //待办事项状态
                     formMasterId:formDataId,
                     nodePolicy//节点权限
                 },
                 this.params
               )
             )
           )[0].data;
           if (typeof requestData === 'string') {
               this.list = JSON.parse(requestData);
           } else {
               this.list = requestData;
           }
           console.log('list', this.list)
       },
        async requestCashId() {
           let pageCondJSON=[];
            if (this.data.customCondItemList && this.data.customCondItemList.length) {
                pageCondJSON = JSON.stringify(this.data.customCondItemList.filter(item => item.changed));
            }
            const {businessData: {affair}} = this.baseInfo;
            const formDataId = window._getZWIframe().contentAPI.getContentDataId();
            const {id = '', dataTypeName = ''} = this.data;
            return await api.commonRelationCondition({
                drPoId: id,
                affairId: affair.id||'-1',
                recordId: formDataId,
                pageCondJSON,
                dataTypeName
            });
        },
        registerEvent(){
            let zwIframe = window._getZWIframe();
            if (!globalData.isCap4){
                return;
            }
            let registerEventFn = zwIframe?.contentAPI?.registerEvent;
            if (!registerEventFn){
                return;
            }
            //改变事件
            let registerFormEvent= (eventName,callback=()=>{})=>{
                registerEventFn.call(this,eventName,(res)=>{
                    let changeData = {
                        fieldId:res.id,
                        fieldValue:res.value,
                        fieldRecordId:res.recordId,
                        fieldDisplyValue:res.showValue,
                    };
                    
                    let key = res.id;
                    if (res.recordId) {
                        key += "_" + res.recordId;
                    }
                    let formData = {};
                    formData[key] = changeData;
                    try {
                        console.log(`registerEvent ${eventName} trigger`,formData)
                        //TODO eventType = change
                        callback(formData);
                    }catch (e){
                        console.log(`registerEvent ${eventName}`,e)
                    }
                })
            }
            //TODO eventType = change
            //改变事件
            registerFormEvent('afterFormFieldChange',(formData)=>{
                let changed=false;
                console.log(11111, this.data);
                if (this.data.customCondItemList && this.data.customCondItemList.length){
                    this.data.customCondItemList.forEach(condition=>{
                        let formDatum = formData[condition.trunkFieldName];
                        if (formDatum && formDatum.fieldValue !== condition.fieldValue) {
                            //输入值有更新
                            condition.fieldValue = formDatum.fieldValue;
                            condition[condition.trunkFieldName] = condition.trunkFieldName;
                            condition.fieldName = condition.trunkFieldName;
                            condition.changed = true;
                            if (formDatum.fieldRecordId) {
                                condition.fieldRecordId = formDatum.fieldRecordId;
                            }
                            if (this.data.dataTypeName === 'index'){
                                condition.fieldDisplyValue = formDatum.fieldDisplyValue;
                            }
                            changed = true;
                        }
                    })
                }
                if (changed){
                    this.initData(true);
                }
            })
            //TODO  eventType = calcChange
            
            //计算事件
            registerFormEvent('afterFormFieldCalc')
            //重新加载数据 //重复表行删除后事件,重新加载数据
            registerEventFn.call(this,'afterRepeatChange',(res)=>{
               //TODO 重新加载数据
                console.log('registerEvent afterRepeatChange trigger')
            })
        }
    }
};
